package com.zjjt.dc.tools.download.file.action;

import com.zjjt.dc.tools.download.file.pool.DownloadThreadPoolManager;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutorService;

@Slf4j
public class DownloadFileAction {

    private String downloadDir = "./download/";

    public DownloadFileAction() {
    }

    public DownloadFileAction(String downloadDir) {
        this.downloadDir = downloadDir;
    }
    public int action(String agrs[]){
        // 确保下载目录存在
        Path downloadDir = Paths.get(this.downloadDir);
        try {
            Files.createDirectories(downloadDir);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        for (String path : agrs) {
            try {
                downloadFile(path, downloadDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    public int actionThreads(List<String> paths){
        // 确保下载目录存在
        Path downloadDir = Paths.get(this.downloadDir);
        try {
            Files.createDirectories(downloadDir);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        // 提交下载任务到线程池
        for (String path : paths) {
            DownloadThreadPoolManager.getExecutorService().submit(() -> {
                try {
//                    Thread.sleep(500);
                    log.info("开始下载：" + path);
                    downloadFile(path, downloadDir);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        return 0;
    }
    /**
     * 下载单个文件
     * @param fileUrl 文件URL
     * @param downloadDir 下载目录
     */
    private void downloadFile(String fileUrl, Path downloadDir) throws Exception {
        URL url = new URL(fileUrl);
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        Path filePath = downloadDir.resolve(fileName);

        try (InputStream in = url.openStream();
             OutputStream out = Files.newOutputStream(filePath)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }


    public static void close() {
        ExecutorService executorService = DownloadThreadPoolManager.getExecutorService();
        executorService.shutdown();
    }
}
